package com.qf.utils;

import javax.servlet.http.HttpServletRequest;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

public class BeanUtils {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static <T> T processParamters(HttpServletRequest request, Class<T> targetClass) throws IllegalAccessException, InstantiationException, IntrospectionException, ParseException, InvocationTargetException {
        Enumeration<String> parameterNames = request.getParameterNames();
        T instance = targetClass.newInstance();

        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            if ("option".equals(name)) {
                continue;
            }
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, targetClass);
            if (propertyDescriptor != null) {
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (writeMethod != null) {
                    Class<?>[] parameterTypes = writeMethod.getParameterTypes();
                    if (parameterTypes.length > 0) {
                        Class<?> parameterType = parameterTypes[0];
                        if (parameterType == Date.class) {
                            Date date = simpleDateFormat.parse(value);
                            writeMethod.invoke(instance, date);
                            continue;
                        }

                        if (parameterType == String.class){
                            writeMethod.invoke(instance,value);
                            continue;
                        }

                        if (parameterType == Integer.class  || parameterType == int.class){
                            int i = Integer.parseInt(value);
                            writeMethod.invoke(instance, i);
                            continue;
                        }

                        if (parameterType == Long.class || parameterType == long.class){
                            long l = Long.parseLong(value);
                            writeMethod.invoke(instance, l);
                            continue;
                        }
                    }

                }
            }
        }
        return instance;
    }
}
